package com.gome.han.beencloud.jdk.bio.echo.demo1;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;

import com.gome.han.beencloud.Const;

/**
* @author hanpeng
* @version 创建时间：2020年10月27日 下午8:59:36
* @ClassName 类名称
* @Description 类描述
*/
public class BioClient {
	@SuppressWarnings("resource")
	public static void main(String[] args) throws UnknownHostException, IOException  {
		Socket socket = new Socket(Const.DEFAULT_SERVER_IP, Const.DEFAULT_PORT);
		System.out.println("请输入请求信息: ");
		new ReadMsg(socket).start();
		PrintWriter pWriter=null;
		while (true) {
			pWriter=new PrintWriter(socket.getOutputStream());
			pWriter.println(new Scanner(System.in).next());
			pWriter.flush();
		}
	}
	private static class ReadMsg extends Thread {
		private Socket socket;

		public ReadMsg(Socket socket) {
			super();
			this.socket = socket;
		}

		@Override
		public void run() {
			try (
				BufferedReader bReader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
			){
				String line=null;
				while ((line=bReader.readLine())!=null) {
					System.out.printf("%s\n", line);
				}
			} catch (SocketException e) {
				System.out.printf("%s\n", "服务器断开了你的连接");
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				clear();
			}
			
		}
		private void clear() {
			if(socket!=null) {
				try {
					socket.close();
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		}
		
		
	}
}
